<template>
  <div class="timeline-section">
    <!-- 时间范围信息 -->
    <div class="time-range-info">
      <el-form-item label="开始时间:" prop="startTime" class="form-row-item">
        <el-input 
          v-model="timeRange.startTime" 
          placeholder="00:00:00" 
          clearable 
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="结束时间:" prop="endTime" class="form-row-item">
        <el-input 
          v-model="timeRange.endTime" 
          placeholder="00:00:00" 
          clearable 
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="拆条名称:" prop="name" class="form-row-item">
        <el-input 
          v-model="timeRange.name" 
          placeholder="输入拆条名称" 
          clearable 
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="格式:" prop="format" class="form-row-item">
        <el-select 
          v-model="timeRange.format" 
          placeholder="选择格式" 
          style="width: 100%;"
        >
          <el-option label="MP4" value="mp4" />
          <el-option label="FLV" value="flv" />
          <el-option label="MOV" value="mov" />
        </el-select>
      </el-form-item>
      <el-form-item label="画质:" prop="quality" class="form-row-item">
        <el-select 
          v-model="timeRange.quality" 
          placeholder="选择画质" 
          style="width: 100%;"
        >
          <el-option label="高清" value="high" />
          <el-option label="标清" value="standard" />
          <el-option label="流畅" value="smooth" />
        </el-select>
      </el-form-item>
      <el-button 
        type="primary" 
          @click="confirmClipping" 
          :icon="Scissor" 
          class="confirm-btn"
      >
        确认拆条
      </el-button>
    </div>
    
    <!-- 时间轴 -->
    <div class="timeline-wrapper">
      <!-- 时间刻度 -->
      <div class="time-markers">
        <div 
          v-for="marker in timeMarkers" 
          :key="marker.time" 
          :style="{ left: marker.position + '%' }" 
          class="time-marker"
        >
          <div class="marker-line"></div>
          <div class="marker-label">{{ marker.label }}</div>
        </div>
      </div>
      
      <!-- 播放头 -->
      <div 
        class="playhead" 
        :style="{ left: playheadPosition + '%' }"
        @mousedown="onPlayheadMouseDown"
      >
        <div class="playhead-line"></div>
        <div class="playhead-circle"></div>
      </div>
      
      <!-- 时间轴内容 -->
      <div class="timeline-content">
        <!-- 视频缩略图 -->
        <div class="video-thumbnails" v-if="hasThumbnails">
          <div 
            v-for="(thumb, index) in thumbnails" 
            :key="index" 
            class="thumbnail-item"
            :style="{ width: (100 / thumbnails.length) + '%' }"
          >
            <div class="thumbnail-overlay"></div>
          </div>
        </div>
        <!-- 空时间轴 -->
        <div v-else class="empty-timeline">
          <div class="empty-timeline-text">加载视频缩略图中...</div>
        </div>
      </div>
      
      <!-- 时间轴控制按钮 -->
      <div class="timeline-controls">
        <el-button 
          size="small" 
          @click="setStartTime"
          title="设为开始时间"
          icon="ArrowLeft"
        />
        <el-button 
          size="small" 
          @click="setEndTime"
          title="设为结束时间"
          icon="ArrowRight"
        />
        <el-button 
          size="small" 
          @click="resetTimeRange"
          title="重置时间范围"
          icon="Refresh"
        />
        <el-button 
          size="small" 
          @click="fitToScreen"
          title="适配屏幕"
          icon="ZoomIn"
        />
      </div>
    </div>
    
    <!-- 时间信息栏 -->
    <div class="timeline-info-bar">
      <div class="current-time">
        <span>当前时间:</span>
        <span class="time-value">{{ currentTimeDisplay }}</span>
      </div>
      <div class="selected-duration">
        <span>选择时长:</span>
        <span class="time-value">{{ selectedDurationDisplay }}</span>
      </div>
      <div class="total-duration">
        <span>总时长:</span>
        <span class="time-value">{{ formatTime(totalDuration) }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, onMounted, onUnmounted } from 'vue'
import { Scissor, ArrowLeft, ArrowRight, Refresh, ZoomIn } from '@element-plus/icons-vue'

const props = defineProps({
  totalDuration: {
    type: Number,
    default: 0
  },
  currentTime: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['confirmClipping', 'setStartTime', 'setEndTime', 'resetTimeRange', 'fitToScreen'])

const timeRange = ref({
  startTime: '00:00:00',
  endTime: '00:00:00',
  name: '',
  format: 'mp4',
  quality: 'high'
})

const playheadPosition = computed(() => {
  if (props.totalDuration === 0) return 0
  return (props.currentTime / props.totalDuration) * 100
})

const currentTimeDisplay = computed(() => formatTime(props.currentTime))

const selectedDurationDisplay = computed(() => {
  const startSeconds = timeStringToSeconds(timeRange.value.startTime)
  const endSeconds = timeStringToSeconds(timeRange.value.endTime)
  return formatTime(endSeconds - startSeconds)
})

const hasThumbnails = ref(false)
const thumbnails = ref([])
const timeMarkers = ref([])

// 处理时间格式转换
const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) return '00:00:00'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

const timeStringToSeconds = (timeString) => {
  const parts = timeString.split(':').map(Number)
  if (parts.length === 3) {
    return parts[0] * 3600 + parts[1] * 60 + parts[2]
  } else if (parts.length === 2) {
    return parts[0] * 60 + parts[1]
  }
  return 0
}

// 生成时间刻度
const generateTimeMarkers = () => {
  const markers = []
  const markerInterval = Math.max(10, Math.ceil(props.totalDuration / 30)) // 根据总时长调整刻度间隔
  
  for (let t = 0; t <= props.totalDuration; t += markerInterval) {
    markers.push({
      time: t,
      position: (t / props.totalDuration) * 100,
      label: formatTime(t)
    })
  }
  
  timeMarkers.value = markers
}

// 播放头拖动事件
const onPlayheadMouseDown = (event) => {
  event.preventDefault()
  const handleMouseMove = (e) => {
    // 处理鼠标移动事件
  }
  const handleMouseUp = () => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 组件方法
const confirmClipping = () => {
  emit('confirmClipping', timeRange.value)
}

const setStartTime = () => {
  timeRange.value.startTime = currentTimeDisplay.value
  emit('setStartTime', timeRange.value.startTime)
}

const setEndTime = () => {
  timeRange.value.endTime = currentTimeDisplay.value
  emit('setEndTime', timeRange.value.endTime)
}

const resetTimeRange = () => {
  timeRange.value.startTime = '00:00:00'
  timeRange.value.endTime = formatTime(props.totalDuration)
  emit('resetTimeRange')
}

const fitToScreen = () => {
  emit('fitToScreen')
}

// 生命周期
onMounted(() => {
  generateTimeMarkers()
  // 模拟加载缩略图
  setTimeout(() => {
    hasThumbnails.value = true
    thumbnails.value = Array.from({ length: 60 }, (_, i) => ({ id: i }))
  }, 1000)
})

onUnmounted(() => {
  // 清理事件监听等
})
</script>

<style scoped>
.timeline-section {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color);
  border-radius: var(--border-radius-base);
  border-left: 4px solid var(--info-color);
  padding: 12px;
  box-sizing: border-box;
  overflow: hidden;
}

.time-range-info {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--border-light-color);
}

.form-row-item {
  flex: 1;
  min-width: 120px;
  margin-bottom: 0;
}

.confirm-btn {
  margin-left: auto;
  white-space: nowrap;
}

.timeline-wrapper {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-light-color);
  border-radius: var(--border-radius-small);
  overflow: hidden;
  margin-bottom: 8px;
}

.time-markers {
  height: 20px;
  position: relative;
  background-color: var(--bg-color);
  border-bottom: 1px solid var(--border-color);
}

.time-marker {
  position: absolute;
  top: 0;
  transform: translateX(-50%);
  width: 1px;
  height: 100%;
}

.marker-line {
  height: 6px;
  background-color: var(--border-color);
  margin: 0 auto;
  width: 1px;
}

.marker-label {
  position: absolute;
  top: 8px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 10px;
  color: var(--text-secondary-color);
  white-space: nowrap;
}

.playhead {
  position: absolute;
  top: 0;
  height: 100%;
  transform: translateX(-50%);
  z-index: 200;
  cursor: ew-resize;
}

.playhead-line {
  height: 100%;
  width: 1px;
  background-color: var(--primary-color);
  margin: 0 auto;
}

.playhead-circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: var(--primary-color);
  border: 2px solid #FFFFFF;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.timeline-content {
  flex: 1;
  position: relative;
  overflow: hidden;
  background-color: var(--bg-light-color);
}

.video-thumbnails {
  width: 100%;
  height: 100%;
  display: flex;
}

.thumbnail-item {
  height: 100%;
  background-color: var(--bg-color);
  border-right: 1px solid var(--border-light-color);
  position: relative;
  transition: all 0.2s ease;
}

.thumbnail-item:hover {
  background-color: rgba(24, 144, 255, 0.05);
}

.thumbnail-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, rgba(24, 144, 255, 0.1) 0%, rgba(24, 144, 255, 0) 100%);
}

.empty-timeline {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-placeholder-color);
  font-style: italic;
  font-size: 12px;
}

.timeline-controls {
  height: 30px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px;
  background-color: var(--bg-color);
  border-top: 1px solid var(--border-light-color);
}

.timeline-controls .el-button {
  height: 24px;
  line-height: 24px;
  padding: 0 8px;
  font-size: 12px;
}

.timeline-info-bar {
  display: flex;
  gap: 24px;
  padding: 8px 0;
  font-size: 12px;
  color: var(--text-secondary-color);
  overflow-x: hidden;
  width: 100%;
}

.current-time,
.selected-duration,
.total-duration {
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
}

.time-value {
  color: var(--text-color);
  font-family: 'Consolas', 'Monaco', monospace;
  font-weight: 500;
}

@media (max-width: 1200px) {
  .time-range-info {
    flex-wrap: wrap;
  }
  
  .form-row-item {
    min-width: 100px;
  }
  
  .timeline-info-bar {
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .time-range-info {
    flex-direction: column;
  }
  
  .form-row-item {
    min-width: 100%;
  }
  
  .confirm-btn {
    margin-left: 0;
    width: 100%;
  }
  
  .timeline-info-bar {
    flex-direction: column;
    gap: 4px;
  }
}
</style>